package com.example.mvitest.mvi

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mvitest.mvi.repository.DataRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class MviViewModel : ViewModel() {
    //事件
    private val _eventShareFlow = MutableSharedFlow<MviViewEvent>()
    val eventShareFlow:SharedFlow<MviViewEvent> = _eventShareFlow
    //状态
    private val _statusLiveData = MutableLiveData<MviViewState>()
    val statusLiveData:LiveData<MviViewState> = _statusLiveData


    private var count = 0

    init {
        viewModelScope.launch {
            _statusLiveData.value = MviViewState(ActionStatus.LoadingInit, emptyList())
        }
    }

    //处理数据
    fun handleData(viewAction:ActionView){
        when(viewAction){
            ActionView.OnRefresh->refreshData(count++)
            ActionView.LoadData->loadData()
            is ActionView.ItemClick-> itemClick(viewAction.item)
        }
    }

    private fun refreshData(count:Int){
        viewModelScope.launch(Dispatchers.Main) {
            flow {
                val data = DataRepository.instance.refreshData(count)
                val state = MviViewState(ActionStatus.LoadingSuccess,data)
                kotlinx.coroutines.delay(100)
                emit(state)
            }
                .onStart {
                    emit(MviViewState(ActionStatus.LoadingInit))
                }.onCompletion {
                    emit(MviViewState(ActionStatus.LoadingFinish))
                }.flowOn(Dispatchers.IO)
                .collect {
                    _statusLiveData.value = it
                }
        }
    }

    private fun loadData(){
        viewModelScope.launch(Dispatchers.Main) {
            flow {
                val data = DataRepository.instance.fetchData()
                val state = MviViewState(ActionStatus.LoadingSuccess,data)
                kotlinx.coroutines.delay(100)
                emit(state)
            }
                .onStart {
                    emit(MviViewState(ActionStatus.LoadingInit))
                }.onCompletion {
                    emit(MviViewState(ActionStatus.LoadingFinish))
                }.flowOn(Dispatchers.IO)
                .collect {
                    _statusLiveData.value = it
                }
        }
    }

    private fun itemClick(message:String){
        viewModelScope.launch {
            _eventShareFlow.emit(MviViewEvent.ShowToast(message))
        }
    }

}